﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection;
using ZingFrameworkCore.Common.Injection;

namespace ZingFrameworkCore.Data.EntityFramwork
{
    public class MySqlDbContext : DbContext
    {
        private readonly IConfiguration _configuration;
        public MySqlDbContext(DbContextOptions options) : base(options)
        {
            _configuration = ServiceProviderAccessor.ServiceProvider.GetService<IConfiguration>();
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var assemblyName = _configuration["Entities:AssemblyName"];
            var _namespace = _configuration["Entities:Namespace"];
            Assembly.Load(new AssemblyName(assemblyName))
                .GetTypes()
                .Where(p => p.Namespace.Contains(_namespace))
                .ToList()
                .ForEach((p) =>
                {
                    if (modelBuilder.Model.FindEntityType(p) == null)
                    {
                        modelBuilder.Model.AddEntityType(p);
                    }
                });
            base.OnModelCreating(modelBuilder);
        }

        public override EntityEntry<TEntity> Update<TEntity>(TEntity entity)
        {
            this.Set<TEntity>().Attach(entity);
            var props = entity.GetType().GetProperties();
            props.ToList().ForEach((prop) =>
            {
                if (prop.GetValue(entity, null) != null)
                {
                    if (prop.GetValue(entity, null).ToString() == "&nbsp;")
                    {
                        this.Entry(entity).Property(prop.Name).CurrentValue = null;
                    }
                    if (prop.Name != "F_Id")
                    {
                        this.Entry(entity).Property(prop.Name).IsModified = true;
                    }
                }
            });
            return default(EntityEntry<TEntity>);
        }
        
    }
}
